#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <string>
using namespace std;
using namespace cv;
Mat checkImageY(Mat &image, int size);
Mat checkImageX(Mat &image, int size);
void sortArray(int *p, int length);
///////////////////////////为图像添加椒月噪声///////////
int main() {
    Mat src = imread("/home/dao/桌面/week04/src/first.png");
    Mat dst;
    cvtColor(src, dst, COLOR_BGR2GRAY);
    Mat dstResultX = checkImageX(dst, 3);
    Mat dstResultY = checkImageY(dst, 3);
    imshow("灰度图像", dst);
    imshow("原图像", src);
    imshow("边缘检测X", dstResultX);
    imshow("边缘检测Y", dstResultY);
    waitKey(0);
}
Mat checkImageX(Mat &image, int size) {
    // size创建的对象常常用来存储图向的宽度与高度
    Mat image_clone = image.clone();
    //对卷及核的合理性判断
    if (size % 2 == 0) {
        cout << "请输入一个有效的尺寸" << endl;
        return image_clone;
    }
    //对原图像进行扩充
    int addH = (size - 1) / 2;  //计算扩充高度
    int addW = (size - 1) / 2;  //计算扩充高度
    Mat newimage;
    copyMakeBorder(image, newimage, addW, addW, addH, addH, BORDER_DEFAULT);

    for (int i = addH; i < image.rows + addH; i++) {
        for (int j = addW; j < image.cols + addW; j++) {
            if (image.type() == CV_8UC1) {
                int result = -1 * newimage.at<uchar>(i - 1, j - 1) - 2 * newimage.at<uchar>(i - 1, j) -
                             1 * newimage.at<uchar>(i - 1, j + 1) + newimage.at<uchar>(i + 1, j - 1) +
                             2 * newimage.at<uchar>(i + 1, j) + newimage.at<uchar>(i + 1, j + 1);
                image_clone.at<uchar>(i - addH, j - addW) = result;
            }
        }
    }
    return image_clone;
}
Mat checkImageY(Mat &image, int size) {
    // size创建的对象常常用来存储图向的宽度与高度
    Mat image_clone = image.clone();
    //对卷及核的合理性判断
    if (size % 2 == 0) {
        cout << "请输入一个有效的尺寸" << endl;
        return image_clone;
    }
    //对原图像进行扩充
    int addH = (size - 1) / 2;  //计算扩充高度
    int addW = (size - 1) / 2;  //计算扩充高度
    Mat newimage;
    copyMakeBorder(image, newimage, addW, addW, addH, addH, BORDER_DEFAULT);

    for (int i = addH; i < image.rows + addH; i++) {
        for (int j = addW; j < image.cols + addW; j++) {
            if (image.type() == CV_8UC1) {
                int result = -1 * newimage.at<uchar>(i - 1, j - 1) - 2 * newimage.at<uchar>(i, j - 1) -
                             1 * newimage.at<uchar>(i + 1, j - 1) + newimage.at<uchar>(i - 1, j + 1) +
                             2 * newimage.at<uchar>(i - 1, j + 1) + newimage.at<uchar>(i - 1, j + 1);
                image_clone.at<uchar>(i - addH, j - addW) = result;
            }
        }
    }
    return image_clone;
}

void sortArray(int *p, int length) {
    for (int i = 0; i < length - 1; i++) {
        for (int j = 1; j < length - i; j++) {
            if (p[j - 1] < p[j]) {
                int temp = p[j];
                p[j] = p[j - 1];
                p[j - 1] = temp;
            }
        }
    }
}
